/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2024-03-26 16:12:11
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2025-02-08 17:56:28
 * @FilePath: /vue3-admin/src/views/system/UsersManage/useTable.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { ref } from 'vue';
import { useUser } from '@/service/biz/useUser';
import { useEnum, type ExtractObservableType } from '@/service/useEnum';
import { useUserStore } from '@/store';
import { usePermission } from '@/service/usePermission';

class ListParam {
    current = 1;
    size = 10;
    username = '';
    status?: 1 | 0;
    roleId?: number;
    departmentId?: number;
}

export const useTable = () => {
    const { list, total, loading, getList: getUserList } = useUser();

    const { updatePermission } = usePermission();

    const { userInfo } = useUserStore();

    const {
        validTypes,
        roleTypeSource,
        roleTypeUpdate,
        deptTreeUpdate,
        deptTreeSource
    } = useEnum();

    const listParam = ref(new ListParam());

    const statusTypes = validTypes;

    const roleTypes = ref<ExtractObservableType<typeof roleTypeSource>>([]);
    const roleTypeSubscription = roleTypeSource.subscribe((types) => {
        roleTypes.value = types;
    });
    roleTypeUpdate();

    const deptTreeItems = ref<ExtractObservableType<typeof deptTreeSource>>([]);
    const deptTreeSubscription = deptTreeSource.subscribe((types) => {
        deptTreeItems.value = types;
    });
    deptTreeUpdate();
    const deptCascaderProps = {
        emitPath: false,
        checkStrictly: true
    };

    onBeforeUnmount(() => {
        roleTypeSubscription.unsubscribe();
        deptTreeSubscription.unsubscribe();
    });

    const formatParam = (param: ListParam) => {
        return {
            ...listParam.value,
            valid:
                typeof listParam.value.status === 'number'
                    ? listParam.value.status === 1
                    : undefined
        };
    };

    const getList = () => {
        getUserList(formatParam(listParam.value));
    };

    const reset = () => {
        listParam.value = new ListParam();
        getUserList(formatParam(listParam.value));
    };

    const editShow = ref(false);
    const editId = ref<number>();

    const handleEdit = (id?: number) => {
        editShow.value = true;
        editId.value = id;
    };

    const afterUpdate = () => {
        editShow.value = false;
        getList();
        if (editId.value === userInfo?.id) {
            updatePermission();
        }
    };

    getList();
    return {
        list,
        listParam,
        total,
        loading,
        statusTypes,
        roleTypes,
        deptTreeItems,
        deptCascaderProps,
        getList,
        reset,
        handleEdit,
        editShow,
        editId,
        afterUpdate
    };
};
